// src/api/contractApi.js
import { apiClient } from './base'

// 分页查询合同列表
export const getList = (params = {}) => {
  const { page = 1, size = 20, search, contractType, contractStatus } = params
  const queryParams = new URLSearchParams()
  
  if (page) queryParams.append('page', page)
  if (size) queryParams.append('size', size)
  if (search) queryParams.append('search', search)
  if (contractType) queryParams.append('contractType', contractType)
  if (contractStatus) queryParams.append('contractStatus', contractStatus)
  
  return apiClient.get(`/contracts?${queryParams.toString()}`)
}

// 创建合同
export const create = (contractData) => 
  apiClient.post('/contracts', contractData)

// 根据ID查询合同详情
export const getById = (id) => 
  apiClient.get(`/contracts/${id}`)

// 更新合同
export const update = (id, contractData) => 
  apiClient.put(`/contracts/${id}`, contractData)

// 删除合同
export const deleteById = (id) => 
  apiClient.delete(`/contracts/${id}`)

// 查询合同付款记录
export const getPayments = (contractId) => 
  apiClient.get(`/contracts/${contractId}/payments`)

// 检查合同编号是否存在
export const checkContractNumber = (contractNumber) => 
  apiClient.get(`/contracts/check?contractNumber=${encodeURIComponent(contractNumber)}`)

// 精确查询合同
export const search = (params = {}) => {
  const { contractName, supplierName } = params
  const queryParams = new URLSearchParams()
  
  if (contractName) queryParams.append('contractName', contractName)
  if (supplierName) queryParams.append('supplierName', supplierName)
  
  return apiClient.get(`/contracts/search?${queryParams.toString()}`)
}

// 导出Excel
export const exportData = (params) => {
  const queryParams = new URLSearchParams()
  
  // 添加搜索参数
  if (params.search) {
    queryParams.append('search', params.search)
  }
  
  // 添加合同类型筛选
  if (params.contractType !== null && params.contractType !== undefined) {
    queryParams.append('contractType', params.contractType)
  }
  
  // 添加合同状态筛选
  if (params.contractStatus !== null && params.contractStatus !== undefined) {
    queryParams.append('contractStatus', params.contractStatus)
  }
  
  const url = `/contracts/export${queryParams.toString() ? `?${queryParams.toString()}` : ''}`
  
  return apiClient.get(url, { 
    responseType: 'blob'
  })
}

// 默认导出
export default {
  getList,
  create,
  getById,
  update,
  delete: deleteById,
  getPayments,
  checkContractNumber,
  search,
  export: exportData
}